package com.ruoyi.web.core.utils;

import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.io.FileUtil;

import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.ruoyi.web.core.config.OssConfig;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.io.FileUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Formatter;
import java.util.LinkedHashMap;
import java.util.Map;

import static com.ruoyi.common.utils.file.FileUploadUtils.extractFilename;


public class OSSUtil {

    // Endpoint以华南3（广州）为例，其它Region请按实际情况填写。
    static String endpoint = OssConfig.END_POINT;
    // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
    static String accessKeyId = OssConfig.ACCESS_KEY_ID;
    static String accessKeySecret = OssConfig.ACCESS_KEY_SECRET;
    // 填写Bucket名称，例如examplebucket。
    static String bucketName = OssConfig.BUCKET_NAME;

    //前端直传
    public static Map<String,Object> Policy() {
        // 填写Host地址，格式为https://bucketname.endpoint。
        String host = "https://city-partner.oss-cn-shanghai.aliyuncs.com";
        // 设置上传到OSS文件的前缀，可置空此项。置空后，文件将上传至Bucket的根目录下。
        String format = new SimpleDateFormat("yyyy:MM:hh").format(new Date());
        String dir = "city"+"/";
        Map<String, Object> respMap = null;
        try {
            long expireTime = 6000;
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);
            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = ossClient.calculatePostSignature(postPolicy);

            respMap = new LinkedHashMap<String, Object>();
            respMap.put("accessid", accessKeyId);
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            respMap.put("dir", dir);
            respMap.put("host", host);
            respMap.put("expire", String.valueOf(expireEndTime / 1000));

        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return respMap;
    }




    //不压缩
    public static String uploadFile2(MultipartFile multiFile) throws IOException {

        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        //获取文件名称
        String filename = extractFilename(multiFile);
        try {
            // 获取上传文件的输入流
            InputStream inputStream = multiFile.getInputStream();
            //获取文件名
            filename = "city/" + filename;
            //调用OSS方法实现上传
            //第一个参数 Bucket名称
            //第二个参数  上传到OSS文件路径和文件名称
            //第三个参数  上传文件输入流
            ossClient.putObject(bucketName, filename, inputStream);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return filename;
    }

}
